'''
Created on 19 Jan 2010

@author: yusuf
'''
from collections import deque
from smpplib import client
from loader import Loader
import threading, time

class Receiver(threading.Thread):
    '''
    classdocs
    '''
    

    def __init__(self, loader):
        '''
        Constructor
        '''
        self.incoming = loader.getQ()
        self.myclient = client.Client('rbfep01', 5100)
        self.loader = loader
        threading.Thread.__init__ ( self )
        
    def run(self):
        self.startListening()
        while self.loader.isAlive():
            time.sleep(10)
        self.shutDown()
         
    def startListening(self):
        self.myclient.connect()
        print "Connected..."
        self.myclient.bind_receiver(system_id='SYSID', password='pass123', system_type='TEST')
        self.myclient.set_message_received_handler(self.recv_handler)
        self.myclient.listen()
     
    def getQ(self):
        return self.incoming
    
    def recv_handler(self,**args):
        print 'Message received:'
        msg = args['pdu']
        print "Message: "+msg.short_message
        print "From: "+msg.source_addr
        print "To: " +msg.destination_addr
        message = [msg.source_addr,msg.destination_addr,msg.short_message]
        self.incoming.append(message)
        #self.logger.log(message)
        #print "Service Type: " +msg.service_type
        #print "Source ton: " +msg.source_addr_ton
        #print "Source npi: " +msg.source_addr_npi
        #print "Dest ton: " +msg.dest_addr_ton
        #print "Dest npi: " +msg.dest_addr_npi
        #print "esm class: " +msg.esm_class
        #print "Protocol ID: " +msg.protocol_id
        #print "Priority Flag: " +msg.priority_flag
        #print "Sched Delivery Time: " +msg.schedule_delivery_time
        #print "Message Validity: " +msg.validity_period
        #print "Registered Delivery: " +msg.registered_delivery
        #print "Replace if present: " +msg.replace_if_present_flag
        #print "Data Coding: " +msg.data_coding
        #print "Default Msg ID: " +msg.sm_default_msg_id
        #print "Message Length: " +msg.sm_length
        
    def shutDown(self):
        #client.unbind()
        self.myclient.disconnect()
        print "Disconnected..."
        
if __name__ == "__main__":
    load = Loader()
    load.start()
    rec = Receiver(load)
    try:
        rec.start()
    except KeyboardInterrupt:
        print "Stopping..."
        rec.shutDown()
        load.shutDown()